package org.springframework.extend.persistence.repository.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.extend.persistence.repository.ExtendXmlPersistenceRepository;
import org.springframework.extend.persistence.repository.SqlResource;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class SqlRepositoryBeanDefinitionParser extends AbstractExtendBeanDefinitionParser implements
		BeanDefinitionParser {

	public BeanDefinition parse(Element element, ParserContext context) {
		RootBeanDefinition repositoryBeanDef = newRootBeanDefinition(element, context,
				ExtendXmlPersistenceRepository.class);
		MutablePropertyValues propertyValues = repositoryBeanDef.getPropertyValues();

		// build sql resource
		NodeList sqlResources = element.getElementsByTagName("sql");

		if (hasNode(sqlResources)) {
			int resourceLenth = sqlResources.getLength();
			Map<String, SqlResource> resources = new HashMap<String, SqlResource>();

			for (int index = 0; index < resourceLenth; index++) {
				Node n = sqlResources.item(index);

				SqlResource resource = new SqlResource(n.getAttributes().getNamedItem("id").getNodeValue(), n
						.getTextContent());
				resources.put(resource.getId(), resource);
			}
			propertyValues.addPropertyValue("resources", resources);
		}

		BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(repositoryBeanDef, "repository"),
				context.getRegistry());

		return repositoryBeanDef;
	}
}
